package dao;

import entity.Grades;
import entity.IEntity;
import entity.Student;
import entity.Subject;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import vo.GradesVO;

/**
 *
 * @author Alexander
 */
public class GradesDAO implements IDAO {

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IEntity find(Object id, EntityManager em) {
        return (Grades) em.find(Grades.class, (int) id);
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    @Override
    public void delete(Object id, EntityManager em) {
        Grades calif = (Grades) em.getReference(Grades.class, (int) id);
        em.remove(calif);
    }

    @Override
    public List<IEntity> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Grades.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }

    public List<Grades> findByUser(Student user, EntityManager em) {
        List<Grades> grad = new ArrayList<>();
        Query q = em.createQuery("SELECT g "
                + "FROM Grades g "
                + "WHERE g.group.subject.calendar.student = :user").setParameter("user", user);

        grad = q.getResultList();

        return grad;
    }

    public List<GradesVO> gradesList(String user, Integer subjCode, EntityManager em){
        List<GradesVO> grades = null;
        Subject sub = null;
        Query qs = em.createQuery("SELECT s FROM Subject s "
                + "WHERE s.code = :code").setParameter("code", subjCode);
        Query q = em.createQuery("SELECT cg.grades "
                + "FROM ClassGroup cg "
                + "WHERE cg.subject = :subj");
                      
        try{
            sub = (Subject) qs.getSingleResult();
            q.setParameter("subj", sub);
            grades = (List<GradesVO>) q.getResultList();
        }
        catch(NonUniqueResultException nex){
            sub = (Subject) qs.getResultList().get(0);
        }
        catch(NoResultException nrex){
            grades = null;
        }
        
        return grades;
    }
}
